package com.authine.cloudpivot.ext.applicationservice;

import com.alibaba.cola.dto.RequestContext;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.BizException;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.client.utils.JSONUtils;
import com.authine.cloudpivot.ext.applicationservice.base.ApplicationBaseService;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.dto.ApprovalFlowStrategyDto;
import com.authine.cloudpivot.ext.dto.BatchSubmitDto;
import com.authine.cloudpivot.ext.dto.LogisticsDto;
import com.authine.cloudpivot.ext.dto.system.UserDto;
import com.authine.cloudpivot.ext.eum.ApprovalMailUtis;
import com.authine.cloudpivot.ext.utils.BoUtils;
import com.authine.cloudpivot.ext.utils.StringUtils;
import com.authine.cloudpivot.ext.utils.boQuery.BoQueryUtils;
import com.authine.cloudpivot.ext.utils.email.MailUtis;
import com.authine.cloudpivot.ext.utils.logistics.LogisticsUtils;
import com.authine.hermes.app.flow.engine.impl.persistence.entity.WorkItemEntity;
import com.authine.hermes.app.flow.runtime.dto.clientobject.HandleWorkItemValidMessageVO;
import com.authine.mvp.app.launcher.domain.SelectorFormat;
import com.authine.mvp.app.launcher.domain.utills.ApplicationContextUtils;
import com.authine.mvp.app.launcher.dto.bo.query.LoadBOQuery;
import com.authine.mvp.app.launcher.dto.bo.response.BO;
import com.authine.mvp.app.launcher.dto.bo.response.BOList;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.map.HashedMap;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.*;
import java.util.stream.Collectors;

import static com.authine.hermes.app.launcher.service.ApplicationServiceFoundation.CUSTOM_SERVICE;

@Path("ApprovalFlowStrategyService")
@Slf4j
public class ApprovalFlowStrategyService extends ApplicationBaseService {

    private final NamedParameterJdbcTemplate jdbcTemplate = ApplicationContextUtils.getBean(NamedParameterJdbcTemplate.class);

    @Path("queryParticipant")
    @POST
    @Operation(summary = "流程审批管理-获取节点参与者", tags = CUSTOM_SERVICE, description = "流程节点flowNode、流程编码workflowCode、organization所属组织必填，订单流程flow_type为1")
    public List<String> queryParticipant(@Parameter ApprovalFlowStrategyDto dto) {
        List<String> result = new ArrayList<>();
        if (dto == null) {
            throw new BizException("流程审批策略信息必填");
        }
        log.info("流程策略传参ApprovalFlowStrategyDto::{}", JSON.toJSONString(dto));
        List<String> participant = new ArrayList<>();
        //根据业务bizObjectId查询上一节点处理人
        log.info("当前登陆人id::{},当前登陆人姓名::{}", JSON.toJSONString(RequestContext.getCorpLoginId()),RequestContext.getLoginRealName());
        participant.add(StringUtils.isBlank(dto.getLoginId())?RequestContext.getCorpLoginId():dto.getLoginId());
        dto.setParticipant(participant);
        SingleResponse<BOList> singleResponse = BoQueryUtils.Builder(ModelConst.T_APPROVAL_FLOW_STRATEGY)
                .condition()
                .eq("child_flow_node", dto.getFlowNode())
                .eq("workflow_code", dto.getWorkflowCode())
                .eq("flow_type", dto.getFlowType())
                .eq("organization", dto.getOrganization().get(0))
                .End().listBO();
        List<Map<String, Object>> approvalFlowStrategyList = singleResponse.getData().getData();
        if (approvalFlowStrategyList.isEmpty()) {
            throw new BizException("策略为空，请联系管理员添加流程策略");
        }
        log.info("返回流程策略approvalFlowStrategyList::{}", JSON.toJSONString(approvalFlowStrategyList));
        for (Map<String, Object> f : approvalFlowStrategyList) {
            List<SelectorFormat> participants = (List<SelectorFormat>) f.get("participant");
            log.info("上一节点所有participants::{}", JSON.toJSONString(participants));
            log.info("上一节点participant::{}", JSON.toJSONString(dto.getParticipant()));
            List<String> participantsStr = participants.stream().map(SelectorFormat::getId).collect(Collectors.toList());
            log.info("上一节点所有participantsStr::{}", JSON.toJSONString(participantsStr));
            if (participantsStr.contains(dto.getParticipant().get(0))) {
                log.info("存在参与者participant");
                List<SelectorFormat> person = (List<SelectorFormat>) f.get("child_node_participant");
                if (CollectionUtils.isNotEmpty(person)) {
                    result.addAll(person.stream().map(SelectorFormat::getId).collect(Collectors.toList()));
                }
            }
        }
        //新建线程并执行任务类
        new Thread(() -> {
            log.info("异步调用发邮件待办人::{}", JSON.toJSONString(result));
            if (CollectionUtils.isNotEmpty(result)){
                String subject="待审批审批通知";
                String message="";
                if (dto.getWorkflowCode().equals("1")||dto.getFlowType().equals("1")) {
                    subject="订单审批通知";
                }
                if (dto.getWorkflowCode().equals("2")||dto.getFlowType().equals("2")) {
                    subject="定标审批通知";
                }
                Map<String, Object> parameter = new HashMap<>();
                parameter.put("ids",result);
                String sql="select * from systemmanagement.i_systemmanagement_t_user where deleted=0 and id in (:ids)";
                List<Map<String, Object>> userList = jdbcTemplate.queryForList(sql,parameter);
                for (Map<String,Object> entity : userList) {
                    log.info("待收邮件人信息entity::{}", JSON.toJSONString(entity));
                    message="尊敬的"+entity.get("fullname")+"！您有待订单审批待处理！";
                    ApprovalMailUtis.sendEmail(entity.get("email").toString(),subject,message,2);
                }
            }
        }).start();
        return result;
    }

    @Path("batchSubmitApproval")
    @POST
    @Operation(summary = "定标流程审批管理-批量审批", tags = CUSTOM_SERVICE, description = "批量审批")
    public SingleResponse<HandleWorkItemValidMessageVO>  batchSubmitApproval(@Parameter BatchSubmitDto batchSubmitDto) {
        if (batchSubmitDto == null) {
            throw new BizException("批量审批信息必填！！");
        }
        log.info("定标流程审批管理-批量审批batchSubmitDto::{}", JSON.toJSONString(batchSubmitDto));
        return workflowService.batchSubmit(batchSubmitDto.getUserId(),batchSubmitDto.getWorkItemIds(), batchSubmitDto.getContent(),batchSubmitDto.getResources());
    }
}
